package com.zyp.ubil;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DriverUtil {
    //1.定义成员变量
    public static DataSource dataSource;

    //2.静态代码块
    static {
        try {
            //3.创建属性集对象
            Properties p = new Properties();
            //4.加载配置文件 Druid 连接池不能主动加载配置文件，需要指定文件
            InputStream inputStream = DriverUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            //5.Properties 对象的Load方法从字节流中读取信息
            p.load(inputStream);

            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接的方法
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取连接池对象
    public static DataSource getDataSource(){
        return dataSource;
    }

    //5.关闭连接，释放资源
    public static void close(Connection con){
        if (con !=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement statement) {
        if (con != null && statement != null) {
            try {
                //归还连接
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }



    public static void close(Connection con, Statement statement, ResultSet resultSet) {
        if (con != null && statement != null) {
            try {
                //归还连接
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
